<template>
    <div style="display: flex;justify-content: space-between;">
        <a-form size="small" :model="pageData" layout="inline" style="margin-bottom: 10px;" ref="formRef">
            <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader" />
            <a-form-item label="日期">
                <a-range-picker class="bacClass" v-model="pageData.createTimeArr" style="width:260px" />
            </a-form-item>
        </a-form>
        <Toolbar v-if="tabKey === 1" :items="['查询']" @select="selectHandle" @print="printPdf"></Toolbar>
        <Toolbar v-if="tabKey === 2" :items="['查询', '打印']" @select="selectHandle" @print="printPdf"></Toolbar>
    </div>
    <div class="cssTable">
        <a-tabs :lazy-load="true" :justify="true" :default-active-key="tabKey" @change="tabChange">
            <a-tab-pane title="待结案" :key="1">
                <a-spin :loading="pageData.pageLoading" tip="加载中" dot
                    style="height:100%;width: 98%;z-index:999 ;margin-left: 13px;">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        :style="{ height: pageData.rHeight - 180 + 'px' }" :suppressDragLeaveHidesColumns="true"
                        rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="pageData.tableList" :columnDefs="tableColumns"
                        :localeText="localeText1"></AgGridVuesCopys>
                </a-spin>
            </a-tab-pane>
            <a-tab-pane title="已结案" :key="2">
                <a-spin :loading="pageData.pageLoading" tip="加载中" dot
                    style="height:100%;width: 98%;z-index:999 ;margin-left: 13px;">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        :style="{ height: pageData.rHeight - 220 + 'px' }" :suppressDragLeaveHidesColumns="true"
                        rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="pageData.tableList" :columnDefs="tableColumns"
                        :localeText="localeText1"></AgGridVuesCopys>
                </a-spin>
            </a-tab-pane>
        </a-tabs>
    </div>
    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
        @change="PageSize" @page-size-change="change1" style="justify-content: center;margin-top:12px;"
        :page-size="size" :current="page" />

    <!-- 跟进事项 -->
    <a-drawer style="z-index:999" :drawer-style="{ 'zIndex': 999 }" :mask-closable="false"
        popup-container=".arco-tabs-content" height="100%" :visible="pageData.itemsVisible" placement="bottom"
        unmountOnClose @cancel="pageData.itemsVisible = false">
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <el-button :icon="EditPen" @click="itemFill()" type="primary"
            v-if="tabKey === 1 && pageData.sideTitle === '查看跟进事项'">修改</el-button>
        <el-button :icon="CirclePlus" @click="reasonQuery()" type="success"
            v-if="tabKey === 1 && pageData.sideTitle === '跟进事项填写'">选择处理意见</el-button>
        <el-button :icon="CirclePlus" @click="addRow()" type="success"
            v-if="tabKey === 1 && pageData.sideTitle === '跟进事项填写'">新增行</el-button>
        <el-button :icon="Delete" @click="delRow()"
            v-if="tabKey === 1 && pageData.sideTitle === '跟进事项填写'">删除</el-button>
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
            :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReadyGJ"
            style="height:93%;margin-top: 10px;" :defaultColDef="defaultColDef2" class="ag-theme-alpine"
            :rowData="pageData.itemsList" :columnDefs="tableColumnsGJ" :localeText="localeText1">
        </AgGridVuesCopys>
        <template #footer>
            <a-button @click="pageData.itemsVisible = false">取消</a-button>
            <a-button type="primary" @click="handleOK" v-if="tabKey === 1">保存</a-button>
        </template>
    </a-drawer>

    <!-- 处理意见 -->
    <a-drawer style="z-index:999" :drawer-style="{ 'zIndex': 999 }" :mask-closable="false"
        popup-container=".arco-tabs-content" height="100%" :visible="pageData.reasonVisible" placement="bottom"
        unmountOnClose @cancel="pageData.reasonVisible = false">
        <template #title>选择处理意见</template>
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
            :suppressDragLeaveHidesColumns="true" style="height:92%;margin-top: 10px;" @grid-ready="gridReadyCL"
            :defaultColDef="defaultColDef2" class='ag-theme-alpine' :rowData="pageData.reasonList"
            :columnDefs="tableColumnsCL" :localeText="localeText1">
        </AgGridVuesCopys>
        <template #footer>
            <a-button @click="pageData.reasonVisible = false">取消</a-button>
            <a-button type="primary" @click="reasonSelect">确定</a-button>
        </template>
    </a-drawer>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, Ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { FormInstance } from "@arco-design/web-vue/es/form";
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import printJS from 'print-js'
import { Search, CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
    rHeight: 0,
    pageLoading: false,
    tableList: [],
    sideTitle: '',
    itemsList: [],
    companyId: null,
    companyName: '',
    handlerDepartmentCodes: null,
    createTimeArr: null,
    itemsVisible: false,
    status: null,
    problemId: null,
    orderList: [],
    handleCompanyId: null,
    reasonVisible: false,
    reasonList: [],
})

//分页
const total = ref(0);
const page = ref(1);
const size = ref(10);
function PageSize(val: any) {
    page.value = val
    doRefresh();
}
function change1(val: any) {
    size.value = val
    doRefresh();
}

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
}

//事故数据
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}
const tableColumns: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    {
        headerName: "来源",
        width: 150,
        cellRenderer: {
            template: `<span> {{ val.createUser=== 'SYN' ? '系统创建' : '手动创建' }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
    },
    { headerName: "事故单号", field: "problemCode", width: 150, },
    { headerName: "日期", field: "createTime", width: 150, },
    { headerName: "公司", field: "companyName", width: 150, },
    { headerName: "部门", field: "departmentName", width: 150, },
    { headerName: "员工工号", field: "staffCode", width: 150, },
    { headerName: "员工姓名", field: "staffName", width: 150, },
    { headerName: "机台号", field: "machineCode", width: 150, },
    { headerName: "织布单号", field: "planOrderCode", width: 150, },
    { headerName: "坯布编号", field: "greyCode", width: 150, },
    { headerName: "坯布名称", field: "greyName", width: 150, },
    {
        headerName: "数量",
        width: 150,
        cellRenderer: () => {
            return "<span>" + 1 + "</span>";
        },
    },
    {
        headerName: "单位",
        width: 150,
        cellRenderer: () => {
            return "<span>" + '匹' + "</span>";
        },
    },
    { headerName: "问题原因", field: "defectReason", width: 150, },
    { headerName: "问题补充", field: "questionSupplement", width: 150, },
    {
        headerName: "疵布重量",
        field: "lowLevelWeight",
        width: 150,
    },
    {
        headerName: "实际转数",
        width: 150,
        cellRenderer: (params: any) => {
            let val = params.data.convolution1 + params.data.convolution2
            return "<span>" + val + "</span>";
        },
    },
    { headerName: "责任工序", field: "handlerOrderNames", width: 150, },
    {
        headerName: "审核意见",
        field: "rejectReason",
        width: 150,
        pinned: 'right',
    },
    {
        headerName: "操作",
        field: "action",
        width: 160,
        pinned: 'right',
        cellRenderer: {
            template: `<a-space>
                           <el-button style="color:#165dff;" link @click="c">跟进事项</el-button>
                       </a-space>`,
            setup(props: any) {
                const c = () => {
                    itemQuery(props.params.data)
                }
                return {
                    c,
                    pageData
                }
            },
        },
    },
]

//跟进事项列表
const gridOptionGJ = ref()
const gridReadyGJ = (params: any) => {
    gridOptionGJ.value = params.api
}
const tableColumnsGJ: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    {
        headerName: "跟进原因事项",
        field: "problemReason",
        width: 300,
        cellRenderer: {
            template: `<a-input :max-length="200" v-if="pageData.sideTitle === '跟进事项填写'" class="bacClass" v-model="val.problemReason" allow-clear></a-input>
                       <span v-else>{{ val.problemReason }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "责任人",
        field: "handleEmployeeCode",
        width: 300,
        cellRenderer: {
            template: `<el-select v-if="pageData.sideTitle === '跟进事项填写'" v-model="val.handleEmployeeCode" multiple filterable clearable placeholder=" " 
                        :collapse-tags="true" :collapse-tags-tooltip="true" class="bacClass" style="width:230px;" @change="c">
                           <el-option v-for="item in pageData.orderList" :key="item.code" :label="item.departmentName + '/' + item.name" :value="item.code" />
                       </el-select>
                       <span v-else>{{ val.handleEmployeeName }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                const c = () => {
                    userChange(props.params.data)
                }
                return {
                    c,
                    getUsers,
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "计划完成时间",
        field: "completeTime",
        width: 160,
        cellRenderer: {
            template: ` <a-date-picker v-if="pageData.sideTitle === '跟进事项填写'" v-model="val.completeTime" class="bacClass" format="YYYY-MM-DD 23:59:59" />
                        <span v-else>{{ val.completeTime }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "状态",
        field: "status",
        width: 160,
        cellRenderer: {
            template: `<a-select v-if="pageData.sideTitle === '跟进事项填写'" popup-container="html" class="bacClass" v-model="val.status" allow-clear>
                           <a-option :value="0">未完成</a-option>
                           <a-option :value="1">已完成</a-option>
                           <a-option :value="2">已完成(其他)</a-option>
                       </a-select>
                       <span v-else>{{ val.status === 0 ? '未完成' : val.status === 1 ?'已完成' : '已完成(其他)' }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value === 0 ? '未完成' : params.value === 1 ? '已完成' : '已完成(其他)'
            },
        }
    },
    {
        headerName: "备注",
        field: "remark",
        width: 190,
        cellRenderer: {
            template: `<a-input v-if="pageData.sideTitle === '跟进事项填写'" class="bacClass" v-model="val.remark" allow-clear></a-input>
                       <span v-else>{{ val.remark }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "实际完成时间",
        field: "finishTime",
        width: 160,
        cellRenderer: {
            template: ` <a-date-picker v-if="pageData.sideTitle === '跟进事项填写'" v-model="val.finishTime" class="bacClass" format="YYYY-MM-DD 23:59:59" />
                        <span v-else>{{ val.finishTime }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
]

//处理意见列表
const gridOptionCL = ref()
const gridReadyCL = (params: any) => {
    gridOptionCL.value = params.api
}
const tableColumnsCL: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    { headerName: "责任工序", field: "employeeName", width: 150 },
    { headerName: "原因分析", field: "problemReason", width: 150 },
    { headerName: "预防措施", field: "preventMeasure", width: 150 },
    { headerName: "处理方法", field: "resolution", width: 150 },
    {
        headerName: "图片",
        field: "problemImg",
        width: 150,
        cellRenderer: {
            template: ` <a-image v-if="val.problemImg" :src="val.problemImg" /> 
                        <span v-if="!val.problemImg">暂无图片</span>`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                };
            },
        },
    },
]

const defaultColDef2: any = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1
}

//查询
const formRef = ref<FormInstance>();
function doRefresh() {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            pageData.pageLoading = true
            post({
                url: '/qms/qualityProblem/pagedQualityProblems',
                data: {
                    current: page.value,
                    size: size.value,
                    status: tabKey.value === 1 ? 5 : 6,
                    companyId: pageData.companyId,
                    handlerDepartmentCodes: pageData.handlerDepartmentCodes === '' ? null : pageData.handlerDepartmentCodes,
                    beginTime: pageData.createTimeArr == undefined ? null : pageData.createTimeArr[0] + ' 00:00:00',
                    endTime: pageData.createTimeArr == undefined ? null : pageData.createTimeArr[1] + ' 23:59:59'
                }
            }).then((res: any) => {
                if (res.code === 200) {
                    pageData.tableList = res.data.records
                    total.value = res.data.total
                }
            }).catch(console.log).finally(() => {
                pageData.pageLoading = false
            })
        }
    })
}

let tabKey = ref(1)
const tabChange = (e: any) => {
    tabKey.value = e
    page.value = 1
    doRefresh()
}

const selectHandle = () => {
    page.value = 1
    doRefresh()
}

//查看跟进事项
const itemQuery = (val: any) => {
    pageData.status = val.status
    pageData.handleCompanyId = val.companyId
    pageData.problemId = val.id
    getUsers('')
    post({
        url: '/qms/finalResolution/listFinalResolutions',
        data: {
            problemId: pageData.problemId
        }
    }).then((res: any) => {
        if (res.code === 200) {
            pageData.itemsList = res.data
            if (pageData.itemsList.length === 0) {
                pageData.sideTitle = '跟进事项填写'
            } else {
                pageData.itemsList.forEach((item: any) => {
                    item['isTypeIds'] = isTypeIds++
                })
                pageData.sideTitle = '查看跟进事项'
            }
            pageData.itemsVisible = true
        }
    })
}


//新增
let isTypeIds = 0
const addRow = () => {
    pageData.itemsList.push({
        'problemReason': '',
        'handleEmployeeCode': '',
        'completeTime': '',
        'status': 0,
        'remark': '',
        'finishTime': '',
        'isTypeIds': isTypeIds++
    })
    setTimeout(function () { gridOptionGJ.value.setRowData(pageData.itemsList) }, 0)
}

//删除
const delRow = () => {
    if (gridOptionGJ.value.getSelectedRows().length == 0) {
        Message.warning('请选择要删除的数据！')
        return
    }
    let deleteId = pageData.itemsList.map((item: any) => item.isTypeIds);
    let deleteIds = gridOptionGJ.value.getSelectedRows().map((item: any) => item.isTypeIds);
    let list = deleteId.filter((ids: any) => deleteIds.includes(ids));
    pageData.itemsList = pageData.itemsList.filter((item: any) => !list.includes(item.isTypeIds));
}


//跟进事项填写
const itemFill = () => {
    if (pageData.itemsList.length === 0) {
        pageData.itemsList.push({
            'problemReason': '',
            'handleEmployeeCode': '',
            'completeTime': '',
            'status': 0,
            'remark': '',
            'finishTime': '',
            'isTypeIds': isTypeIds++
        })
    } else {
        pageData.itemsList.forEach((o: any) => {
            o.handleEmployeeCode = o.handleEmployeeCode.split(',')
            o.handleEmployeeName = o.handleEmployeeName.split(',')
        });
    }
    pageData.sideTitle = '跟进事项填写'
}

const handleOK = () => {
    if (pageData.itemsList.length === 0) {
        Message.warning('请填写跟进事项！')
        return
    }
    if (pageData.itemsList.some((o: any) => o.problemReason === '')) {
        Message.warning('跟进原因事项必填！')
        return
    }
    if (pageData.itemsList.some((o: any) => o.handleEmployeeCode === '')) {
        Message.warning('责任人必填！')
        return
    }
    if (pageData.itemsList.some((o: any) => o.completeTime === '')) {
        Message.warning('计划完成时间必填！')
        return
    }
    if (pageData.itemsList.some((o: any) => o.status === null)) {
        Message.warning('状态必填！')
        return
    }
    if (pageData.itemsList.some((o: any) => o.status === 2 && o.remark === '')) {
        Message.warning('备注必填！')
        return
    }
    if (pageData.itemsList.some((o: any) => (o.status === 1 || o.status === 2) && !o.finishTime)) {
        Message.warning('实际完成时间必填！');
        return;
    }

    let data = JSON.parse(JSON.stringify(pageData.itemsList))
    data.forEach((o: any) => {
        o.id = null
        o.problemId = pageData.problemId
        if (o.handleEmployeeName && Array.isArray(o.handleEmployeeName)) {
            o.handleEmployeeName = o.handleEmployeeName.join(',')
            o.handleEmployeeCode = o.handleEmployeeCode.join(',')
        }
    })
    if (data.some((o: any) => o.status === 0)) {
        post({
            url: '/qms/finalResolution/saveOrUpdateFinalResolution',
            data: data
        }).then((res: any) => {
            if (res.code === 200) {
                Message.success("保存成功");
                pageData.itemsVisible = false
                pageData.itemsList = []
            }
        })
    } else {
        Modal.confirm({
            title: "系统提示",
            content: "所有跟进事项状态已完成，事故单将自动结案，后续不可修改，是否提交?",
            onOk() {
                post({
                    url: "/qms/finalResolution/saveOrUpdateFinalResolution",
                    data: data
                }).then(({ code, message }: any) => {
                    if (code === 200) {
                        Message.success("保存成功");
                        pageData.itemsVisible = false
                        pageData.itemsList = []
                        doRefresh()
                    } else {
                        Message.error(message);
                    }
                });
            },
        });
    }
}

//选择处理意见
const reasonQuery = () => {
    pageData.reasonVisible = true
    post({
        url: '/qms/qualityResolution/listQualityResolutions',
        data: {
            problemId: pageData.problemId
        }
    }).then((res: any) => {
        if (res.code === 200) {
            pageData.reasonList = res.data
        }
    })
}

const reasonSelect = () => {
    if (gridOptionCL.value.getSelectedRows().length === 0) {
        Message.warning('请先选择数据!')
        return
    }
    let selectData = gridOptionCL.value.getSelectedRows().map((o: any) => {
        let findName = pageData.orderList.find((code: any) => o.employeeCode === code.code)
        return {
            handleEmployeeCode: o.employeeCode.split(','),
            handleEmployeeName: (findName.departmentName + '/' + findName.name).split(','),
            problemReason: o.problemReason,
            completeTime: '',
            status: null,
            remark: '',
            isTypeIds: isTypeIds++
        };
    });
    pageData.itemsList = [...pageData.itemsList, ...selectData];
    pageData.reasonVisible = false
}



//公司
const configCascader = ref<{}>({
    corporateWidth: '230px', //公司宽度
    sectorWidth: '230px', //部门宽度
    corporateRquired: false, //公司是否必填
    size: 'small',
    corporateName: '公司', //公司label
    sectorName: '责任单位', //部门label
    cascaderShow: '', //配置部门不显示

})
const changeCascader = (data: any) => {
    const { corporateId, corporateLabel, sectorId } = data
    pageData.companyId = corporateId
    pageData.companyName = corporateLabel
    pageData.handlerDepartmentCodes = sectorId
}

//员工
const getUsers = (val: any) => {
    pageData.pageLoading = true
    post({
        url: 'org/hrEmployee/getList',
        data: {
            deleteState: 0,
            obsoleteState: 0,
            company_id: pageData.handleCompanyId == undefined ? '' : pageData.handleCompanyId,
            department_id: '',
            ygText: val,
        }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.orderList = data
        } else {
            Message.error({
                content: '该部门无员工信息！',
                duration: 5000,
            })
        }
    })
    pageData.pageLoading = false
}

const userChange = (val: any) => {
    if (val.handleEmployeeCode.length !== 0) {
        val.handleEmployeeName = val.handleEmployeeCode.map((o1: any) => {
            const data = pageData.orderList.find((o: any) => o1 === o.code);
            return data ? (data.departmentName + '/' + data.name) : '';
        });
    } else {
        val.handleEmployeeName = ''
    }
}


//打印预览PDF
const printPdf = () => {
    if (gridOption.value.getSelectedRows().length == 0) {
        Message.error('请先勾选')
        return
    }
    if (gridOption.value.getSelectedRows().length > 1) {
        Message.error('只能勾选一条数据')
        return
    }
    get({
        url: '/qms/qualityProblem/printQualityProblemReport?id=' + gridOption.value.getSelectedRows()[0].id,
        responseType: 'blob'
    }).then((res) => {
        let reader = new FileReader();
        reader.readAsDataURL(res);
        reader.onload = function () {
            let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '');
            printJS({ printable: pdfBase64, type: 'pdf', base64: true })
        };
    });
}

onMounted(() => {
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    selectHandle()
})
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag) {
    color: #4e5969 !important;
    ;
    background-color: white;
    border-color: white;
    font-size: 14px
}

:deep(.arco-image-img) {
    height: 25px;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
    box-shadow: 0 0 0 0 gray !important;
}

:deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0 gray !important;
    padding: 0
}
</style>